package com.member.server.service.impl;

import com.member.server.domain.dto.MemAccInfoDTO;
import com.member.server.domain.dto.MemAccLogInfoDTO;
import com.member.server.domain.param.PagingQueryParam;
import com.member.server.domain.param.QueryParam;
import com.member.server.entity.Account;
import com.member.server.entity.AccountLog;
import com.member.server.entity.Member;
import com.member.server.entity.Record;
import com.member.server.mapper.AccountLogMapper;
import com.member.server.mapper.AccountMapper;
import com.member.server.mapper.MemberMapper;
import com.member.server.mapper.RecordMapper;
import com.member.server.service.IAccountQueryService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author gaojx1993
 * @version 1.0
 * @description IAccountQueryServiceImpl
 * @since 2023/7/12 11:43
 */
@Service
public class IAccountQueryServiceImpl implements IAccountQueryService {

    @Resource
    private MemberMapper memberMapper;

    @Resource
    private AccountMapper accountMapper;

    @Resource
    private AccountLogMapper accountLogMapper;

    @Resource
    private RecordMapper recordMapper;

    @Override
    public MemAccInfoDTO queryMemberAccount(QueryParam queryParam) {
        Member member = memberMapper.selectById(queryParam.getId());
        if (member == null) {
            throw new RuntimeException("会员不存在");
        }
        List<Account> accounts = accountMapper.selectByMemberId(member.getId());
        return new MemAccInfoDTO(member, accounts);
    }

    @Override
    public MemAccLogInfoDTO queryMemberAccountLogs(PagingQueryParam queryParam) {
        Member member = memberMapper.selectById(queryParam.getId());
        if (member == null) {
            throw new RuntimeException("会员不存在");
        }
        // 获取钱包信息
        List<Account> accounts = accountMapper.selectByMemberId(member.getId());
        Set<Long> accountIds = accounts.stream().map(Account::getId).collect(Collectors.toSet());
        // 获取钱包余额变动记录
        List<AccountLog> accountLogs = accountLogMapper.selectByAccountIds(accountIds, queryParam.getOffset(), queryParam.getPageSize());
        // 获取流水记录
        List<Record> records = recordMapper.selectByIds(accountLogs.stream().map(AccountLog::getRecordId).collect(Collectors.toSet()));

        return new MemAccLogInfoDTO(member, accounts, accountLogs, records);
    }
}
